package fr.toto.settings;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Phaser;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;

import fr.toto.constantes.Constantes;
import fr.toto.settings.defaultPanels.JDirectories;
import fr.toto.settings.defaultPanels.JDirectory;
import fr.toto.settings.defaultPanels.PanelListString;
import fr.toto.settings.settingPanels.PanelFormatSortie;
import fr.toto.settings.settingPanels.PanelSelectLang;
import fr.toto.settings.settingPanels.PanelWebUI;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class SettingsUI implements Constantes {

	JFrame frame;
	private Phaser phaser;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					try {
						if (Files.exists(SETTINGSPATH)) {
							InputStream in = Files.newInputStream(SETTINGSPATH,
									StandardOpenOption.READ);
							settings.loadFromXML(in);
						}
					} catch (IOException e1) {
						e1.printStackTrace();
					}
					SettingsUI window = new SettingsUI();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public SettingsUI() {
		phaser = new Phaser();
		this.phaser.register();
		initialize();
		frame.setVisible(true);
	}

	public SettingsUI(Phaser phaser) {
		this.phaser = phaser;
		this.phaser.register();

		initialize();
		frame.setVisible(true);
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {

		/**
		 * Déclaration des 'Boites' utilisés
		 */
		final JCheckBox recursifCheckBox;
		final JTextField regexSubAccept;
		final JTextField regexSubRefuse;
		final JCheckBox chckbxDEBUG;
		final JDirectories scanDirectories;
		final JDirectory destDirectory;
		final JDirectories readDirectories;
		final PanelFormatSortie panel_2;
		final PanelWebUI panel_WebUI;
		final PanelSelectLang panel_SelectLang;
		final PanelListString panel_VideoExt;

		/**
		 * Création de la fenêtre de paramétrages
		 */
		frame = new JFrame();
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				phaser.arriveAndDeregister();
			}
		});
		frame.setBounds(100, 100, 600, 700);
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.getContentPane().setLayout(new BorderLayout(0, 0));

		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		frame.getContentPane().add(tabbedPane);

		JScrollPane scrollPane = new JScrollPane();
		tabbedPane.addTab("Dossiers", null, scrollPane, null);

		JPanel panel = new JPanel();
		scrollPane.setViewportView(panel);
		GridBagLayout gbl_panel = new GridBagLayout();
		gbl_panel.columnWidths = new int[] { 493, 0 };
		gbl_panel.rowHeights = new int[] { 131, 23, 2, 131, 0, 131, 0, 0 };
		gbl_panel.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
		gbl_panel.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
				0.0, Double.MIN_VALUE };
		panel.setLayout(gbl_panel);

		scanDirectories = new JDirectories("Dossiers à Scanner :",
				settings.getScanDir());
		GridBagConstraints gbc_scanDirectories = new GridBagConstraints();
		gbc_scanDirectories.gridheight = 3;
		gbc_scanDirectories.fill = GridBagConstraints.BOTH;
		gbc_scanDirectories.insets = new Insets(0, 0, 5, 0);
		gbc_scanDirectories.gridx = 0;
		gbc_scanDirectories.gridy = 0;
		panel.add(scanDirectories, gbc_scanDirectories);

		recursifCheckBox = new JCheckBox("Recherche Récurcive");
		recursifCheckBox.setSelected(settings.isRecursiveScan());
		GridBagConstraints gbc_recursifCheckBox = new GridBagConstraints();
		gbc_recursifCheckBox.anchor = GridBagConstraints.NORTHWEST;
		gbc_recursifCheckBox.insets = new Insets(0, 0, 5, 0);
		gbc_recursifCheckBox.gridx = 0;
		gbc_recursifCheckBox.gridy = 3;
		panel.add(recursifCheckBox, gbc_recursifCheckBox);

		destDirectory = new JDirectory("Dossiers de destination :",
				settings.getDestDir());
		GridBagConstraints gbc_destDirectory = new GridBagConstraints();
		gbc_destDirectory.fill = GridBagConstraints.HORIZONTAL;
		gbc_destDirectory.anchor = GridBagConstraints.SOUTH;
		gbc_destDirectory.insets = new Insets(0, 0, 5, 0);
		gbc_destDirectory.gridx = 0;
		gbc_destDirectory.gridy = 3;
		panel.add(destDirectory, gbc_destDirectory);

		readDirectories = new JDirectories("Dossiers pour la lecture :",
				settings.getReadList());
		GridBagConstraints gbc_readDirectories = new GridBagConstraints();
		gbc_readDirectories.gridheight = 3;
		gbc_readDirectories.fill = GridBagConstraints.BOTH;
		gbc_readDirectories.gridx = 0;
		gbc_readDirectories.gridy = 4;
		panel.add(readDirectories, gbc_readDirectories);

		JScrollPane scrollPane_1 = new JScrollPane();
		tabbedPane.addTab("Format de sortie", null, scrollPane_1, null);

		/***
		 * Réglages Format des fichiers en sorties
		 */
		panel_2 = new PanelFormatSortie(settings.getFormatFile());
		scrollPane_1.setViewportView(panel_2);

		/***
		 * Autres Options
		 */
		JScrollPane scrollPane_2 = new JScrollPane();
		tabbedPane.addTab("Autres Options", null, scrollPane_2, null);

		JPanel panel_12 = new JPanel();
		// panel_12.setMaximumSize(new Dimension(500, 32767));
		scrollPane_2.setViewportView(panel_12);

		/**
		 * Réglages Interface Web
		 */
		panel_WebUI = new PanelWebUI(settings.useWebUI(),
				String.valueOf(settings.getPortWebUI()));
		// panel_WebUI.setMaximumSize(new Dimension(520, 40));
		// panel_WebUI.setAlignmentY(Component.CENTER_ALIGNMENT);

		/***
		 * Réglages Choix langues des soustitres à télécharger
		 */
		panel_SelectLang = new PanelSelectLang(settings.getSubLang());
		// panel_SelectLang.setMaximumSize(new Dimension(520, 60));
		// panel_SelectLang.setPreferredSize(new Dimension(200, 60));
		// panel_SelectLang.setMinimumSize(new Dimension(100, 60));

		/**
		 * Réglages Extentions vidéos acceptées
		 */
		panel_VideoExt = new PanelListString("Extentions Vidéos acceptés :",
				settings.getExtVideo());
		// panel_VideoExt.setAlignmentY(Component.TOP_ALIGNMENT);
		// panel_VideoExt.setMaximumSize(new Dimension(520, 150));

		panel_12.setLayout(new BoxLayout(panel_12, BoxLayout.PAGE_AXIS));
		panel_12.add(panel_WebUI);
		panel_12.add(panel_SelectLang);
		panel_12.add(panel_VideoExt);

		JPanel panel_SubRegex = new JPanel();
		// panel_SubRegex.setAlignmentY(Component.TOP_ALIGNMENT);
		panel_SubRegex.setMaximumSize(new Dimension(100000, 90));
		panel_SubRegex.setLayout(new GridLayout(4, 1, 0, 0));

		JLabel lblNewLabel_4 = new JLabel(
				"Accepte les soustitres avec l'éxpression régulière :");
		panel_SubRegex.add(lblNewLabel_4);

		regexSubAccept = new JTextField();
		regexSubAccept.setText(settings.getSubRegexWith());
		panel_SubRegex.add(regexSubAccept);
		regexSubAccept.setColumns(10);

		JLabel lblNewLabel_5 = new JLabel(
				"Refuse les soustitres avec l'éxpression régulière :");
		panel_SubRegex.add(lblNewLabel_5);

		regexSubRefuse = new JTextField();
		regexSubRefuse.setText(settings.getSubRegexWithout());
		panel_SubRegex.add(regexSubRefuse);
		regexSubRefuse.setColumns(10);

		panel_12.add(panel_SubRegex);

		JPanel panel_16 = new JPanel();
		FlowLayout flowLayout = (FlowLayout) panel_16.getLayout();
		flowLayout.setAlignment(FlowLayout.LEFT);
		panel_16.setMaximumSize(new Dimension(10000, 30));
		panel_12.add(panel_16);

		chckbxDEBUG = new JCheckBox("Activer le mode Debug");
		chckbxDEBUG.setSelected(settings.isDebug());
		panel_16.add(chckbxDEBUG);

		JPanel panel_1 = new JPanel();
		frame.getContentPane().add(panel_1, BorderLayout.SOUTH);
		panel_1.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));

		JButton cancelButton = new JButton("Annuler");
		cancelButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				frame.dispose();
				phaser.arriveAndDeregister();
			}
		});
		panel_1.add(cancelButton);

		JButton validButton = new JButton("Valider");
		validButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				settings.setDebug(chckbxDEBUG.isSelected());
				settings.setDestDir(destDirectory.getPath());
				settings.setExtVideo(panel_VideoExt.getList());
				settings.setFormatFile(panel_2.FormatSortie());
				settings.setReadDir(readDirectories.getList());
				settings.setRecursiveScan(recursifCheckBox.isSelected());
				settings.setScanDir(scanDirectories.getList());
				settings.setSubLang(panel_SelectLang.getSelectedLangue());
				settings.setSubRegexWith(regexSubAccept.getText());
				settings.setSubRegexWithout(regexSubRefuse.getText());
				settings.setWebUI(panel_WebUI.isOn());
				settings.setWebUIPort(panel_WebUI.getPort());
				OutputStream out = null;
				try {
					out = Files.newOutputStream(SETTINGSPATH,
							StandardOpenOption.CREATE,
							StandardOpenOption.TRUNCATE_EXISTING);
					settings.storeToXML(out);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				frame.dispose();
				phaser.arriveAndDeregister();
			}
		});
		panel_1.add(validButton);

	}
}
